﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Adex;
using System.Transactions;
using System.Configuration;


namespace MediaMonitor.Common
{

    /// <summary>
    /// Summary description for Cart
    /// </summary>
    public class Cart
    {
        public Cart()
        {

        }


        public static OrderDetailCollection GetCart()
        {
            //HttpContext h = new HttpContext();
            if (HttpContext.Current.Session["colCartItems"] != null)
            {
                OrderDetailCollection colCartItems = ((OrderDetailCollection)(HttpContext.Current.Session["colCartItems"]));

                return colCartItems;

            }
            else
            {

                return GetNewCart();
            }
        }

        private static void SaveCart(OrderDetailCollection colOrderDetail)
        {
            HttpContext.Current.Session["colCartItems"] = colOrderDetail;
        }

        private static OrderDetailCollection GetNewCart()
        {
            HttpContext.Current.Session["colCartItems"] = null;
            OrderDetailCollection colCartItems = new OrderDetailCollection();
            HttpContext.Current.Session["colCartItems"] = colCartItems;

            return colCartItems;

        }

        public static bool AddItem(OrderDetail item)
        {
            OrderDetailCollection colOrderDetail = GetCart();


            if (colOrderDetail.Find("ProdVersionID", item.ProdVersionID) > -1)
            {
                return false; // i-e: item already in the cart
            };

            colOrderDetail.Add(item);
            SaveCart(colOrderDetail);

            return true;
        }

        public static void RemoveItem(int ProdVersionCode)
        {

            OrderDetailCollection colOrderDetail = GetCart();

            int itemIndex = colOrderDetail.Find("ProdVersionID", ProdVersionCode);

            if (itemIndex == -1)
            {
                //item not found in the cart.
                return;
            }

            OrderDetail Item2Remove = colOrderDetail[itemIndex];

            colOrderDetail.Remove(Item2Remove);

            SaveCart(colOrderDetail);


        }

        public static void ClearCart()
        {
            OrderDetailCollection colOrderItem = GetCart();
            colOrderItem.Clear();
            SaveCart(colOrderItem);
        }

        public static OrderDetail CreateCartItem(int mediaTypeCode, int prodVersionID, string prodVersionName, int productID, string productName, decimal price, string shortVideoFile, string fullVideoFile, bool shortVideo, bool fullVideo, string pressFile, string outdoorFile, string radioFile, string cableFile, string internetFile)
        {

            OrderDetail newItem = new OrderDetail();
            newItem.MediaTypeCode = mediaTypeCode;
            newItem.ProdVersionID = prodVersionID;
            newItem.ProdVersionName = prodVersionName;
            newItem.ProductID = productID;
            newItem.ProductName = productName;
            newItem.ShortVideoFile = shortVideoFile;
            newItem.FullVideoFile = fullVideoFile;
            newItem.ShortVideo = shortVideo;
            newItem.FullVideo = fullVideo;
            newItem.PressFile = pressFile;
            newItem.OutDoorFile = outdoorFile;
            newItem.RadioFile = radioFile;
            newItem.CableFile = cableFile;
            newItem.Price = price;
            newItem.InternetFile=internetFile;

            return newItem;

        }

        public static decimal GetCartTotal()
        {
            OrderDetailCollection colOrderDetail = GetCart();

            decimal tPrice = 0;

            foreach (OrderDetail itm in colOrderDetail)
            {
                tPrice += Utility.ToDecimal(itm.Price);
            }

            return tPrice;

        }

        public static bool IsValidCartCheckout()
        {
            SiteUser usr = new SiteUser(AppUser.CurrUserID);
            Company comp = new Company(usr.CompanyCode);

            if (comp.UnlimitedCredits)
                return true;

            if (comp.Credits < GetCartTotal())
            {
                return false;
            }
            else
            {
                return true;
            }

        }

        public static bool Checkout(out string msg)
        {

            if (!Cart.IsValidCartCheckout())
            {
                msg = "Your company do not have enough credits to buy you this much amount of items.";
                return false;
            }

            //otherwise
            //place and complete order here

            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(10)))
            {
                using (SubSonic.SharedDbConnectionScope conn = new SubSonic.SharedDbConnectionScope(System.Configuration.ConfigurationManager.ConnectionStrings["DBAdex"].ToString()))
                {

                    try
                    {

                        SiteUser usr = new SiteUser(AppUser.CurrUserID);
                        Company comp = new Company(usr.CompanyCode);

                        decimal orderTotal = Cart.GetCartTotal();

                        Order ord = new Order();
                        ord.SiteUserID = usr.SiteUserID;
                        ord.CompanyCode = usr.CompanyCode;
                        ord.CompanyUnlimitedCredits = comp.UnlimitedCredits;
                        ord.DateAdded = DateTime.Now;
                        ord.DateModified = DateTime.Now;
                        ord.OrderStatus = (byte)Enums.OrderStatus.Completed;
                        ord.OrderTotal = orderTotal;
                        ord.Save();


                        foreach (OrderDetail itm in Cart.GetCart())
                        {
                            itm.OrderID = ord.OrderID;
                            itm.DateModified = DateTime.Now;
                            itm.Save();
                        }


                        if (!comp.UnlimitedCredits)
                            comp.Credits = Convert.ToInt32(comp.Credits - orderTotal);

                        comp.Save();
                        Cart.ClearCart();
                        ts.Complete();

                    }

                    catch (Exception ex)
                    {
                        msg = "Failed to proceed with checkout. " + ex.Message;
                        conn.Dispose();
                        ts.Dispose();
                        return false;
                    }

                }//end conn
            }//end ts

            msg = "Checout completed successfully";
            return true;
        }

        public static int FindOrderByProdVersion(int prodVersionID, int userId)
        {

            ProdVersion prodVersion = new ProdVersion("ProdVersionID", prodVersionID);
            DataTable dtOrders = VOrderDetail.Query().SetSelectList("OrderID").WHERE("SiteUserID", userId).AND("ProdVersionID", prodVersion.ProdVersionID).ExecuteDataSet().Tables[0];

            if (dtOrders.Rows.Count > 0)
            {
                return Utility.ToInt(dtOrders.Rows[0]["OrderID"]);
            }

            return 0;
        }
    }

}